import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../services/app_state_service.dart';
import '../theme/app_theme.dart';
import '../models/period_model.dart';

class MenstrualTrackerWidget extends StatefulWidget {
  final AppStateService appState;
  final VoidCallback? onStateChanged;

  const MenstrualTrackerWidget({
    super.key,
    required this.appState,
    this.onStateChanged,
  });

  @override
  State<MenstrualTrackerWidget> createState() => _MenstrualTrackerWidgetState();
}

class _MenstrualTrackerWidgetState extends State<MenstrualTrackerWidget> {
  
  bool _isPeriodActive = false;
  bool _isLoading = false;
  DateTime? _lastPeriodStart;


  
  final Color _pinkColor = const Color(0xFFE91E63);
  final Color _greyColor = Colors.grey;

  @override
  void initState() {
    super.initState();
    _loadPeriodStatus();
  }

  
  Future<void> _loadPeriodStatus() async {
    setState(() {
      _isLoading = true;
    });

    try {
      
      if (!widget.appState.isInitialized) {
        await widget.appState.initializeApp();
      }

      
      final currentState = widget.appState.isPeriodActive;
      final periodRecords = widget.appState.periodRecords;

      
      if (periodRecords.isNotEmpty) {
        
        final sortedRecords = [...periodRecords]
          ..sort((a, b) => b.date.compareTo(a.date));
        
        final recentPeriod = sortedRecords.firstWhere(
          (record) => record.isPeriod,
          orElse: () => PeriodModel(
            date: DateTime.now(),
            isPeriod: false,
            isOvulation: false,
            isToday: true,
            isPredictedPeriod: false,
            isPossiblePeriod: false,
            weight: null,
          ),
        );
        
        if (recentPeriod.isPeriod) {
          _lastPeriodStart = recentPeriod.date;
        }
      }

      setState(() {
        _isPeriodActive = currentState;
      });
    } catch (e) {
      debugPrint('加载经期状态失败: $e');
      _showErrorSnackBar('加载经期状态失败');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: AppTheme.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withValues(alpha: 0.1),
              spreadRadius: 1,
              blurRadius: 5,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              color: AppTheme.primaryColor,
            ),
            SizedBox(height: 16),
            Text(
              '正在处理中...',
              style: TextStyle(
                color: AppTheme.textSecondary,
                fontSize: 14,
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withValues(alpha: 0.1),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          
          Row(
            children: [
              const Icon(
                Icons.water_drop,
                color: Color(0xFFE91E63),
                size: 24,
              ),
              const SizedBox(width: 8),
              Text(
                
                _isPeriodActive ? '月经走了？' : '月经来了？',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppTheme.textPrimary,
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          
          Row(
            children: [
              
              Expanded(
                child: _buildButton(
                  text: '是',
                  
                  isActive: true,
                  activeColor: _pinkColor,
                  inactiveColor: _greyColor,
                  onTap: () async {
                    if (!_isPeriodActive) {
                      
                      final selectedDate = await _showDatePicker('选择开始日期');
                      if (selectedDate != null) {
                        
                        _lastPeriodStart = selectedDate;
                        
                        setState(() {
                          _isPeriodActive = true;
                        });
                        
                      setState(() {
                        _isLoading = true;
                        _isPeriodActive = true; 

                      });
                      
                      try {
                        await widget.appState.recordPeriodStart(selectedDate, notes: '手动记录');
                        widget.onStateChanged?.call();
                        
                        await _loadPeriodStatus();
                      } catch (e) {
                        _showErrorSnackBar('记录失败: $e');
                        
                        setState(() {
                          _isPeriodActive = false;
                          _lastPeriodStart = null;
                        });
                      } finally {
                        setState(() {
                          _isLoading = false;
                        });
                      }
                      }
                    } else {
                      
                      final selectedDate = await _showDatePicker('什么时候走的？');
                      if (selectedDate != null) {
                        
                        
                        setState(() {
                          _isPeriodActive = false;
                        });
                        
                      setState(() {
                        _isLoading = true;
                        _isPeriodActive = false; 

                      });
                      
                      try {
                        debugPrint('=== 记录经期结束 ===');
                        debugPrint('选择日期: $selectedDate');
                        
                        await widget.appState.recordPeriodEnd(selectedDate);
                        widget.onStateChanged?.call();
                        
                        debugPrint('加载后状态: $_isPeriodActive');
                        
                        await _loadPeriodStatus();
                      } catch (e) {
                        _showErrorSnackBar('记录失败: $e');
                        
                        setState(() {
                          _isPeriodActive = true;
                        });
                      } finally {
                        setState(() {
                          _isLoading = false;
                        });
                      }
                      }
                    }
                  },
                ),
              ),
              const SizedBox(width: 16),
              
              Expanded(
                child: _buildButton(
                  text: '否',
                  
                  isActive: false,
                  activeColor: _pinkColor,
                  inactiveColor: _greyColor,
                  onTap: () {
                    
                    
                  },
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 12),
          
          
          Text(
            _isPeriodActive
                ? '点击"是"记录月经结束日期'
                : '点击"是"记录月经开始日期',
            style: const TextStyle(
              fontSize: 12,
              color: AppTheme.textSecondary,
            ),
          ),
          
          
          if (_lastPeriodStart != null) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: AppTheme.background,
                borderRadius: BorderRadius.circular(6),
              ),
              child: Text(
                '最近经期: ${DateFormat('MM月dd日').format(_lastPeriodStart!)}',
                style: const TextStyle(
                  fontSize: 11,
                  color: AppTheme.textSecondary,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  
  Future<DateTime?> _showDatePicker(String helpText) async {
    return await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime.now().subtract(const Duration(days: 30)),
      lastDate: DateTime.now(),
      locale: const Locale('zh', 'CN'),
      helpText: helpText,
      cancelText: '取消',
      confirmText: '确定',
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: ThemeData.light().copyWith(
            primaryColor: _pinkColor, 

            colorScheme: ColorScheme.light(primary: _pinkColor),
            buttonTheme: const ButtonThemeData(textTheme: ButtonTextTheme.primary),
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
                foregroundColor: _pinkColor,
              ),
            ),
          ),
          child: child ?? const SizedBox(),
        );
      },
    );
  }

  
  Widget _buildButton({
    required String text,
    required bool isActive,
    required Color activeColor,
    required Color inactiveColor,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 48,
        decoration: BoxDecoration(
          
          color: isActive 
              ? activeColor 
              : inactiveColor.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(24),
          border: Border.all(
            color: isActive ? activeColor : inactiveColor,
            width: 2,
          ),
          
          boxShadow: [
            if (isActive)
              BoxShadow(
                color: activeColor.withValues(alpha: 0.3),
                spreadRadius: 2,
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
          ],
        ),
        child: Center(
          child: Text(
            text,
            style: TextStyle(
              color: isActive ? Colors.white : inactiveColor,
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }

  
  void _showErrorSnackBar(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }
}

